package com.longxi.tianjintianbao.ui.activity.main;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;

import com.flyco.tablayout.CommonTabLayout;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.BuildConfig;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.broadcast.MyBroadcastReceiver;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.notification.MyNotification;
import com.longxi.tianjintianbao.ui.activity.approval.ApprovalTabActivity;
import com.longxi.tianjintianbao.ui.activity.assetrepair.AssetRepairActivity;
import com.longxi.tianjintianbao.ui.activity.assetscheck.AssetsActivity;
import com.longxi.tianjintianbao.ui.activity.assetscheck.AssetsWebServiceActivity;
import com.longxi.tianjintianbao.ui.activity.complaint.ComplaintListActivity;
import com.longxi.tianjintianbao.ui.activity.equipment.EquipmentActivity;
import com.longxi.tianjintianbao.ui.activity.goodstraffic.GoodsTrafficListActivity;
import com.longxi.tianjintianbao.ui.activity.houseinspection.HomeInspectionActivity;
import com.longxi.tianjintianbao.ui.activity.maintain.MaintainListActivity;
import com.longxi.tianjintianbao.ui.activity.maintain.MaintainListActivity2;
import com.longxi.tianjintianbao.ui.activity.news.NewsActivity;
import com.longxi.tianjintianbao.ui.activity.patrol.PatrolListActivity2;
import com.longxi.tianjintianbao.ui.activity.quality.QualityListActivity;
import com.longxi.tianjintianbao.ui.activity.rectification.RectificationListActivity;
import com.longxi.tianjintianbao.ui.activity.repair_already.AlreadyRepairListActivity;
import com.longxi.tianjintianbao.ui.activity.task.MyTaskListActivity;
import com.longxi.tianjintianbao.ui.activity.task.TaskListActivity;
import com.longxi.tianjintianbao.ui.activity.task_publish.TaskPublishActivity;
import com.longxi.tianjintianbao.ui.activity.visitor.VisitorListActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.presenter.main.MainAtPresenter;
import com.longxi.tianjintianbao.ui.view.main.IMainAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.pgyersdk.crash.PgyCrashManager;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * fragment展示页
 */
public class MainActivity extends BaseActivity<IMainAtView, MainAtPresenter> implements IMainAtView {
    @BindView(R.id.vp_2)
    ViewPager mVp;

    @BindView(R.id.tl_2)
    CommonTabLayout mCtl;
    private String TAG = "MainActivity";
    public static MainActivity mainActivity = null;
    public MainActivity getInstance(){
        if(mainActivity == null){
            mainActivity = MainActivity.this;
        }
        return mainActivity;
    }

    private long exitTime = 0;//退出按钮时间
    private IntentFilter intentFilter;//网络监听吧
    private MyBroadcastReceiver broadcastReceiver;//自定义广播
    public static boolean isForeground = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        openNotification(getApplication(), bundle);
        if(!"debug".equals(BuildConfig.ENVIRONMENT)){
            AndPermission.with(MyApplication.getInstance())
            .permission(Permission.READ_PHONE_STATE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .permission(Permission.RECORD_AUDIO)
            .onGranted(new Action() {
                @Override
                public void onAction(List<String> permissions) {
                    PgyCrashManager.register();
                }
            })
            .onDenied(new Action() {
                @Override
                public void onAction(List<String> permissions) {
                }
            }).start();
        }
    }

    @Override
    public void initData() {
        super.initData();
        getInstance();
        mPresenter.initViewPager();
        mPresenter.pgyCheck();

        broadcastReceiver = new MyBroadcastReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(AppConst.CONNECTIVITY_CHANGE);
//        intentFilter.addAction(AppConst.PATROL_MESSAGE_RECEIVER);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void initListener() {
    }

    public void showShowBtn(int title){
        if(title == 0){
            return;
        }

        switch (title) {
            case R.string.xwtz:
                jumpToActivity(NewsActivity.class);
                return;
            case R.string.wdsp:
                jumpToActivity(ApprovalTabActivity.class);
                return;
            case R.string.fbrw:
                jumpToActivity(TaskPublishActivity.class);
                return;
            case R.string.fbbx:
                mPresenter.showSelectRepairArea();
                return;
            case R.string.yfrw:
                jumpToActivity(TaskListActivity.class);
                return;
            case R.string.bsbx:
                mPresenter.showRepair();
                return;
            case R.string.tscl:
                jumpToActivity(ComplaintListActivity.class);
                return;
            case R.string.xj:
                jumpToActivity(PatrolListActivity2.class);
                return;
            case R.string.pzjc:
                jumpToActivity(QualityListActivity.class);
                return;
            case R.string.gzzg:
                jumpToActivity(RectificationListActivity.class);
                return;
            case R.string.fkdj:
                jumpToActivity(VisitorListActivity.class);
                return;
            case R.string.wpfx:
                jumpToActivity(AssetRepairActivity.class);
                return;
            case R.string.sb:
                mPresenter.showSelectAss();
                return;
            case R.string.by:
                jumpToActivity(MaintainListActivity2.class);
                return;
            case R.string.nhcb:
                jumpToActivity(AssetsWebServiceActivity.class);
                return;
            case R.string.wdrw:
                jumpToActivity(MyTaskListActivity.class);
                return;
            case R.string.yfbx:
                jumpToActivity(AlreadyRepairListActivity.class);
                return;
            case R.string.wywx:
                mPresenter.showRepair();
                return;
            case R.string.rzyf:
                jumpToActivity(HomeInspectionActivity.class);
                return;
        }

        MyUtils.showToast("功能正在开发中");
    }

    @Override
    protected MainAtPresenter createPresenter() {
        return new MainAtPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public ViewPager getVp() {
        return mVp;
    }

    @Override
    public CommonTabLayout getCtl() {
        return mCtl;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPresenter.onActivityResult(requestCode, resultCode, data);
    }

    public void refreshPatrolMessage(){
        mPresenter.refreshPatrolMessage();
    }

    /**
     * 两秒退出
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                MyUtils.showToast(MyUtils.getString(R.string.press_two_exit));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        isForeground = true;
        mPresenter.isForeground = true;
        mPresenter.nmb();
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        mPresenter.isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(broadcastReceiver);
        mainActivity = null;
        super.onDestroy();
    }

    //刷新工作页消息数量
    public void refreshHomeMessage(){
        mPresenter.refreshHomeMessage();
    }

    //刷新消息页消息数量
    public void refreshMessage(){
        mPresenter.refreshMessage();
    }

    private void openNotification(Context context, Bundle bundle){
        if(bundle == null){
            return;
        }
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        if(extras == null && extras == ""){
            return;
        }
        String billdid = "";
        int type = 0;
        int messageid = 0;

        try {
            JSONObject extrasJson = new JSONObject(extras);
            billdid = extrasJson.optString("billdid");
            type = extrasJson.optInt("type");
            messageid = extrasJson.optInt("messageid");
        } catch (Exception e) {
            LogUtils.d(TAG, "Unexpected: extras is not a valid json" + e.toString());
            return;
        }

        //点击消息需要标记已读未读状态
        mPresenter.mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billtype", type);
            object.put("messageid", messageid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String finalBilldid = billdid;
        int finalType = type;
        ApiRetrofit.getInstance().saveMessageLookOver(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mPresenter.mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse result) {
                mPresenter.mContext.hideWaitingDialog();
                if(result.getCode() == 0){
                    refreshMessage();
                }
                MyNotification.getMyNotificationInstance().jump(context, finalBilldid, finalType);
            }
        });
    }

    public void setMsgCount(int count){
        mPresenter.showMsg(count);
    }

}